package cn.com.interceptors;

import cn.com.Authorization;
import cn.com.beans.PAccount;
import cn.com.beans.PResource;
import cn.com.consts.SystemConst;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.invoke.MethodHandle;
import java.util.List;

@Component
public class SecurityIntercopter implements HandlerInterceptor , SystemConst {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlelMethod = (HandlerMethod) handler;
            Authorization annotation = handlelMethod.getMethodAnnotation(Authorization.class);
            String[] urls = (String[]) AnnotationUtils.getValue(annotation,"url");
            RequestMethod[] methods = (RequestMethod[]) AnnotationUtils.getValue(annotation, "method");
            HttpSession session = request.getSession();
            PAccount account = (PAccount) session.getAttribute(LOGIN_STATUS);
            if(account == null){
                response.sendRedirect(request.getContextPath()+"/login");
                return false;
            }else{
                List<PResource> resources = account.getResources();

                for(PResource resource:resources){
                    for(String url:urls){
                        if(url.equals(resource.getUrl())){
                            if(hasAuthority(request,methods)){
                                return true;
                            }
                            return false;
                        }
                    }

                }
            }
        }
        return false;
    }

    public boolean hasAuthority(HttpServletRequest request,RequestMethod[] methods){
        if(methods.length>0){
            for(RequestMethod method:methods){
                if(method.name().equalsIgnoreCase(request.getMethod())){
                    return true;
                }
            }
            return false;
        }
        return true;
    }
}
